<template>
  <view class="page-certification">
    <view class="header">
      <view class="title">{{ $t('mine.实名认证') }}</view>
      <uni-icons type="left" color="#ffffff" size="24" class="back-icon" @click="handleBack"></uni-icons>
    </view>
    <view class="content" v-if="userInfo.verfyStatus == 1">
      <image src="~@/static/images/mine/certification01.webp" alt="" class="content-img" mode="aspectFill" />
      <view class="text">{{ $t('mine.恭喜您，已完成实名认证') }}！</view>
      <view class="user-info">
        <view class="user-info-item">
          <view class="label">{{ $t('mine.姓名') }}：</view>
          <view class="value">{{ userInfo.realname }}</view>
        </view>
        <view class="user-info-item">
          <view class="label">{{ $t('mine.证件号') }}：</view>
          <view class="value">{{ userInfo.idNum | filterPrivacy }}</view>
        </view>
      </view>
      <view class="desc">*{{ $t('mine.您已实名认证，如需更改请联系客服') }}</view>
    </view>
    <view class="form-wrapper" v-if="userInfo.verfyStatus == -1">
      <uni-forms ref="form" :value="form" labelWidth="80px" class="form" label-position="left">
        <view class="form-title">{{ $t('mine.填写个人信息') }}</view>
        <uni-forms-item name="name" :label="$t('mine.姓名')">
          <uni-easyinput type="txt" v-model="form.name" :placeholder="$t('mine.请输入姓名')" />
        </uni-forms-item>
        <uni-forms-item name="idCard" :label="$t('mine.证件号')">
          <uni-easyinput type="txt" v-model="form.idCard" :placeholder="$t('mine.请输入证件号')" />
        </uni-forms-item>
        <view class="form-title">{{ $t('mine.上传证件') }}</view>
        <view class="card-wrapper">
          <view class="card-item" @click="handleChooseImg('front')">
            <template v-if="!form.front">
              <image src="~@/static/images/mine/upload.png" alt="" class="card-add" mode="aspectFit" />
              <view class="text">{{ this.$t('mine.身份证正面') }}</view>
            </template>
            <image v-else :src="`${imgUrl}${form.front}`" alt="" class="card-img" mode="aspectFit" />
          </view>
          <view class="card-item" @click="handleChooseImg('back')">
            <template v-if="!form.back">
              <image src="~@/static/images/mine/upload.png" alt="" class="card-add" mode="aspectFit" />
              <view class="text">{{ this.$t('mine.身份证反面') }}</view>
            </template>
            <image v-else :src="`${imgUrl}${form.back}`" alt="" class="card-img" mode="aspectFit" />
          </view>
        </view>
        <button type="primary" @click="submit" class="btn">{{ $t('mine.提交') }}</button>
      </uni-forms>
    </view>
    <view class="form-wrapper" v-if="userInfo.verfyStatus == 0">
      <view class="text">{{ $t('mine.您的实名认证正在审核中') }}！</view>
      <view class="desc">{{ $t('mine.请耐心等待，如有疑问请联系客服') }}</view>
    </view>
  </view>
</template>
<script>
  import { getInfo, certification } from '@/api/system/user'
  import config from '@/config'
  import { getToken } from '@/utils/auth'

  export default {
    data() {
      return {
        userInfo: {},
        certify: false,
        form: {
          front: '',
          back: '',
          name: '',
          idCard: ''
        },
        rules: {
          name: {
            rules: [
              {
                required: true,
                errorMessage: this.$t('mine.昵称不能为空')
              }
            ]
          },
          idCard: {
            rules: [
              {
                required: true,
                errorMessage: this.$t('mine.证件号不能为空')
              }
            ]
          }
        },
        imgUrl: config.imgUrl
      }
    },
    onPullDownRefresh() {
      this.getUserInfo()
      uni.stopPullDownRefresh()
    },
    onReady() {
      this.$refs.form && this.$refs.form.setRules(this.rules)
    },
    methods: {
      // 返回
      handleBack() {
        // this.$tab.navigateBack()
        this.$tab.switchTab('/pages/mine/index')
      },
      //用户信息
      getUserInfo() {
        this.$modal.loading('loading', 'loading')
        getInfo()
          .then((response) => {
            let { data } = response.result
            this.userInfo = data || {}
            this.$modal.closeLoading()
          })
          .catch((err) => {
            this.$modal.closeLoading()
          })
      },
      //上传证件照
      handleChooseImg(type) {
        uni.chooseImage({
          success: (res) => {
            let imageSrc = res.tempFilePaths
            const baseUrl = config.baseUrl
            const uploadTask = uni.uploadFile({
              url: baseUrl + '/business/upload',
              filePath: imageSrc[0],
              name: 'file',
              header: {
                'x-api-key': getToken()
              },
              success: (uploadRes) => {
                let { statusCode, data } = uploadRes
                data = JSON.parse(data)
                let { message } = data
                if (statusCode == 200) {
                  this.$set(this.form, type, message)
                } else {
                  uni.showToast({
                    title: message
                  })
                }
              },
              fail: (err) => {
                console.error('上传失败', err)
              }
            })
          }
        })
      },
      //提交
      submit() {
        this.$refs.form.validate().then((res) => {
          if (!this.form.front || !this.form.back) {
            this.$modal.msgError(this.$t('mine.请上传证件照'))
            return
          }
          let postForm = {
            realname: this.form.name,
            id_font: this.form.front,
            id_back: this.form.back,
            id_num: this.form.idCard
          }
          certification(postForm).then((response) => {
            this.$modal.msgSuccess(this.$t('mine.修改成功'))
            this.getUserInfo()
          })
        })
      }
    },
    created() {
      this.getUserInfo()
    },
    filters: {
      filterPrivacy(val) {
        function maskString(str, options = {}) {
          if (!str) return ''
          const {
            preserveStart = 4, // 保留开头的字符数
            preserveEnd = 4, // 保留结尾的字符数
            maskChar = '*', // 掩码字符
            maskLength = null, // 自定义掩码长度（可选）
            blockSize = 4, // 分组大小
            separator = '' // 分组分隔符
          } = options
          // 清除所有分隔符（如果需要保留原始分隔符位置，可注释此行）
          const cleanStr = str.replace(/\s/g, '')
          const length = cleanStr.length
          // 处理长度不足的情况
          if (length <= preserveStart + preserveEnd) {
            return cleanStr
          }
          // 计算掩码部分长度
          const maskedLen = maskLength !== null ? Math.min(maskLength, length - preserveStart - preserveEnd) : length - preserveStart - preserveEnd
          // 生成掩码字符串
          const maskedPart = maskChar.repeat(maskedLen)
          // 截取前后保留部分
          const startPart = cleanStr.slice(0, preserveStart)
          const endPart = cleanStr.slice(-preserveEnd)
          // 组合结果
          let result = startPart + maskedPart + endPart
          // 格式化（每blockSize个字符添加一个分隔符）
          if (blockSize > 0 && separator) {
            result = result.match(new RegExp(`.{1,${blockSize}}`, 'g')).join(separator)
          }
          return result
        }
        return maskString(val)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .page-certification {
    position: relative;
    background-color: #f7f7f7;
    min-height: 100vh;
    .header {
      background-color: #31b2b5;
      text-align: center;
      height: 44px;
      line-height: 44px;
      position: fixed;
      top: 0;
      width: 100vw;
      color: #fff;

      font-size: 26rpx;
      z-index: 9;
      .back-icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-weight: normal;
      }
    }
    .content {
      margin: 100rpx 40rpx 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .content-img {
        width: 275px;
        height: 205px;
        margin-top: 50px;
      }
      .text {
        font-size: 28rpx;
        color: #101011;
      }
      .user-info {
        background-color: #31b2b5;
        width: 100%;
        padding: 10px 15px;
        border-radius: 10px;
        margin-top: 75px;
        .user-info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #fff;
          font-size: 26rpx;
          height: 40px;
        }
      }
      .desc {
        font-size: 26rpx;
        color: #666;
        align-self: flex-start;
        margin-top: 15px;
      }
    }
    .form-wrapper {
      margin: 100rpx 20rpx 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .form {
        width: 100%;
        margin-top: 50px;
        .form-title {
          font-size: 36rpx;
          margin-bottom: 36rpx;
        }
        .uni-forms-item {
          background-color: #fff;
          padding: 10rpx 20rpx;
          border-radius: 4px;
          ::v-deep.uni-forms-item__label {
            color: #000;
            font-size: 28rpx !important;
          }
          ::v-deep.uni-easyinput {
            color: #666;
            .is-input-border {
              border: none;
              border-radius: 0;
              padding: 0 10px;
              background-color: #fff !important;
              .uni-input-placeholder,
              .uni-input-input {
                text-align: right;
                color: #ccc;
                font-size: 26rpx !important;
              }
              .uni-input-input {
                color: #000;
              }
            }
          }
          ::v-deep.uni-forms-item__error {
            left: auto;
            right: 0;
          }
        }
        .card-wrapper {
          display: flex;
          .card-item {
            flex: 1;
            height: 260rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 10px;
            border: 1rpx solid #0081ff;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            background-color: #fff;
            &:last-child {
              margin-left: 20rpx;
            }
            .card-add {
              width: 60rpx;
              height: 60rpx;
            }
            .card-img {
              width: 100%;
              height: 100%;
            }
            .text {
              font-size: 32rpx;
              margin-top: 10rpx;
              color: #3d3d3d;
            }
          }
        }
        .btn {
          margin-top: 50rpx;
          background-color: #31b3b5;
        }
      }
    }
  }
</style>
